package sige

import org.springframework.dao.DataIntegrityViolationException

class ResponsavelController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index() {
        redirect(action: "list", params: params)
    }

    def list(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        if(params?.campo){
            String campo = params.campo
            String pesquisa = preparaNome(campo)
            List resultados = Responsavel.findAllByNome(pesquisa, params)
            if(!resultados || resultados?.empty){
                print "nada encontrado"
                flash.message = message(code: 'default.registro.nao.encontrado.message', args: [campo])
            }
            [responsavelInstanceList: resultados, responsavelInstanceTotal: resultados.size(), params: params ]
        }else{
            [responsavelInstanceList: Responsavel.list(params), responsavelInstanceTotal: Responsavel.count()]
        }
    }

    def create(Long id) {
        Contrato contratoInstance = Contrato.get(id)
        [responsavelInstance: new Responsavel(params), contratoInstance: contratoInstance]
    }

    def save(Long contratoId) {
        def responsavelInstance = new Responsavel(params)
        def novoContrato
        if(contratoId){
            novoContrato = Contrato.get(contratoId)
            responsavelInstance.addToContratos(novoContrato)
        }
        
        if (!responsavelInstance.save(flush: true)) {
            render(view: "create", model: [
                responsavelInstance: responsavelInstance, 'contratoInstance': novoContrato])
            return
        }

        flash.message = message(code: 'default.created.message', args: [message(code: 'responsavel.label', default: 'Responsavel'), responsavelInstance.id])
        redirect(action: "show", id: responsavelInstance.id, params: [contratoId: novoContrato.id])
    }

    def show(Long id, Long contratoId) {
        def responsavelInstance = Responsavel.get(id)
        
        if (!responsavelInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'responsavel.label', default: 'Responsavel'), id])
            redirect(action: "list")
            return
        }
        
        if(contratoId){
            println "retornou $contratoId"
            return [responsavelInstance: responsavelInstance, contratoId: contratoId]
        }

        [responsavelInstance: responsavelInstance]
    }

    def edit(Long id) {
        def responsavelInstance = Responsavel.get(id)
        if (!responsavelInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'responsavel.label', default: 'Responsavel'), id])
            redirect(action: "list")
            return
        }

        [responsavelInstance: responsavelInstance]
    }

    def update(Long id, Long version) {
        def responsavelInstance = Responsavel.get(id)
        if (!responsavelInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'responsavel.label', default: 'Responsavel'), id])
            redirect(action: "list")
            return
        }

        if (version != null) {
            if (responsavelInstance.version > version) {
                responsavelInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'responsavel.label', default: 'Responsavel')] as Object[],
                          "Another user has updated this Responsavel while you were editing")
                render(view: "edit", model: [responsavelInstance: responsavelInstance])
                return
            }
        }

        responsavelInstance.properties = params
        if (!responsavelInstance.save(flush: true)) {
            render(view: "edit", model: [responsavelInstance: responsavelInstance])
            return
        }

        flash.message = message(code: 'default.updated.message', args: [message(code: 'responsavel.label', default: 'Responsavel'), responsavelInstance.id])
        redirect(action: "show", id: responsavelInstance.id)
    }

    def delete(Long id) {
        def responsavelInstance = Responsavel.get(id)
        if (!responsavelInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'responsavel.label', default: 'Responsavel'), id])
            redirect(action: "list")
            return
        }

        try {
            responsavelInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'responsavel.label', default: 'Responsavel'), id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'responsavel.label', default: 'Responsavel'), id])
            redirect(action: "show", id: id)
        }
    }
    
    def preencheDados(Long id ){
        def contrato = Contrato.get(id)
        def aluno = Aluno.get(contrato.aluno.id)
        def dadosFamiliares = DadosFamiliares.get(aluno.dadosFamiliares.id)
        
        Responsavel responsavel = new Responsavel()
        println "responsavel1= $responsavel"
        def resp
        if(params.escolha == "pai"){
            resp = "DoPai"
        }else if(params.escolha == 'mae'){
            resp= "DaMae"
        }else{
            return render(template: "form", model:[
                responsavelInstance: responsavel, contratoInstance: contrato])
        }
        
        responsavel.nome = dadosFamiliares."nome$resp"
        responsavel.cpf = dadosFamiliares."cpf$resp"
        responsavel.rg = dadosFamiliares."rg$resp"
        responsavel.email = dadosFamiliares."email$resp"
        responsavel.profissao = dadosFamiliares."profissao$resp"
        println "responsavel= $responsavel"
        render(template: "form", model:[
            responsavelInstance: responsavel, contratoInstance: contrato])
    }
    
    def updateTable = {
        def consulta = preparaNome(params.value)
        def lista = Responsavel.findAllByNomeIlike(consulta)
        
        render (template: 'table', model:[responsavelInstanceList: lista, 
            responsavelInstanceTotal: lista.size()])
    }
    
    private String preparaNome(nome){
        String res = "%"+nome.trim()+"%"
        res.replaceAll(" ", "%")
    }
}
